import { NextResponse } from 'next/server';
import { query } from '@/utils/db';
import { RowDataPacket } from 'mysql2/promise';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';

/**
 * 验证用户密码API
 * POST /api/auth/verify-password
 * 需要登录
 */
export async function POST(request: Request) {
  try {
    // 1. 验证用户是否已登录
    const authHeader = request.headers.get('Authorization');
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json(
        { success: false, message: '未授权访问' },
        { status: 401 }
      );
    }

    // 2. 解析token
    const token = authHeader.substring(7); // 去掉"Bearer "前缀
    const secret = process.env.JWT_SECRET || 'your-secret-key';
    
    let decodedToken;
    try {
      decodedToken = jwt.verify(token, secret);
    } catch (error) {
      return NextResponse.json(
        { success: false, message: '无效的令牌' },
        { status: 401 }
      );
    }

    // 3. 获取请求体中的密码
    const { password } = await request.json();
    if (!password) {
      return NextResponse.json(
        { success: false, message: '密码不能为空' },
        { status: 400 }
      );
    }

    // 4. 查询用户信息
    const userId = (decodedToken as any).id;
    const userQuery = `SELECT id, password FROM users WHERE id = ?`;
    const [userResult] = await query<RowDataPacket[]>(userQuery, [userId]);

    if (!userResult) {
      return NextResponse.json(
        { success: false, message: '用户不存在' },
        { status: 404 }
      );
    }

    // 5. 验证密码
    const passwordMatches = await bcrypt.compare(password, userResult.password);
    if (!passwordMatches) {
      return NextResponse.json(
        { success: false, message: '密码不正确' },
        { status: 400 }
      );
    }

    // 6. 密码验证成功
    return NextResponse.json({
      success: true,
      message: '密码验证成功',
    });
  } catch (error) {
    console.error('密码验证失败:', error);
    return NextResponse.json(
      { success: false, message: '验证过程中发生错误' },
      { status: 500 }
    );
  }
} 